<?php

date_default_timezone_set('Asia/Shanghai');

class BaiDuCommon
{
    private $SOURCE;
    private $SECRET;

    private $API_VERSION;
    private $API_URL;

    private $SHOP_ID;

    public function __construct()
    {
        $this->SOURCE = "65482";
        $this->SECRET = "73c3e84281788e76";

        $this->API_VERSION = 2;
        $this->API_URL = "http://api.waimai.baidu.com";

        $this->SHOP_ID = 1498028450;
    }

    /*
        创建签名
        params
            params 签名数组对象
    */
    public function createSign($params = array())
    {
        $this->_arraySort($params);

        $signStr = json_encode($params);

        return strtoupper(md5($signStr));
    }



    /*
        创建ticket
    */
    public function createTicket()
    {
        $randStr = uniqid(rand(), true);


        $ticket = md5($randStr);
        $ticket = strtoupper($ticket);

        //在左起第8、12、16、20位字符后面添加减号

        //CBB291F633BE57CC8FE3441FE6E7BA6C 
        //CBB291F6-33BE-57CC-8FE3-441FE6E7BA6C
        $ticket = substr_replace($ticket, "-", 8,0);
        $ticket = substr_replace($ticket, "-", 13,0);
        $ticket = substr_replace($ticket, "-", 18,0);
        $ticket = substr_replace($ticket, "-", 23,0);

        return $ticket;
    }

    /*
        获取公共参数
        params
            cmd 命令
            params 传输的参数
    */
    public function getPostData($cmd = '', $params = array())
    {
        $data = array();
        $data['cmd'] = $cmd;
        $data['timestamp'] = time();
        $data['version'] = $this->API_VERSION;
        $data['secret'] = $this->SECRET;
        $data['ticket'] = $this->createTicket();
        $data['source'] = $this->SOURCE;
        $data['body'] = $params;

        $data['sign'] = $this->createSign($data);

        return $data;
    }


    /**
     * 发送请求
     */
    public function _sendReq($data){
        if(is_array($data)){
            $data = @json_encode($data);
        }
        $output = '';
        $retry = 0;
        $userAgent = sprintf('Baidu-Waimai-Openapi-SDK-PHP-%s/%s', $this->API_VERSION, $this->SOURCE);
        $headers = array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($data),
        );
        do{
            $url = sprintf('%s?retry=%s', $this->API_URL, $retry);
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_TIMEOUT, 15);
            curl_setopt($curl, CURLOPT_USERAGENT, $userAgent);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
            $output = curl_exec($curl);
            $info = curl_getinfo($curl);

            curl_close($curl);
            if(isset($info['http_code']) && 200 == $info['http_code']){
                return json_decode($output, true);
            }
            $retry++;
        }while($retry <= $this->_httpRetry && $retry < 10);
        return json_decode($output, true);
    }

    public function DLOG($log_content='', $log_level='', $log_name='')
    { 

        if(empty($log_level)||empty($log_content))
            return;
        
        
        if(empty($log_name) && $log_level == 'run')
            $log_name = 'run';

        $log_dir = "/mnt/logs/";
        $log_file = $log_dir.$log_name.".".date('Y-m-d').".log";
        
        //默认每行日志必写的内容，统一在这里处理
        // ZHANGXI 2015/1/7 for regular
        $time = sprintf("%8s.%03d",date('H:i:s'),floor(microtime()*1000));
        //$time = date('H:i:s').".".floor(microtime()*1000);
        $ip = sprintf("%15s",$_SERVER["REMOTE_ADDR"]);

        $id =   "req-Fn";

        $path_arr = explode("/", $_SERVER['REQUEST_URI']);

        $content_prefix = "[ ".$time." ".$ip." ".$id." ".$log_level." ".$path_arr[1]." ".$path_arr[2]." ] ";

        /*$fp = fopen($log_file, 'a+');
        fwrite($fp, $content_prefix.$log_content." [".getmypid()."]\n");
        fclose($fp);*/

        error_log($content_prefix.$log_content." [".getmypid()."]\n", 3, $log_file);
        return true;
    }

    /**
     * 数组排序
     */
    private function _arraySort(&$arr){
        ksort($arr);
        foreach($arr as &$v){
            if(is_array($v)){
                $this->_arraySort($v);
            }
        }
        return true;
    }
}
?>
